package br.com.players.service;

import java.util.List;

import javax.persistence.Query;

import br.com.players.model.Time;

public class CadastroTimeService extends PlayersService {
	
	public List<Time> listarTimesByCapitao(String capitao) {
		final Query query = em.createQuery("select t from Time t where t.capitao = :capitao");
		query.setParameter("capitao", capitao);
		return (List<Time>) query.getResultList(); 
	}
	
	public List<Time> listarTimes() {
		return (List<Time>) super.findAll(Time.class);
	}
	
	public void inserirTime(Time time) {
		super.persist(time);
	}
	
	public Time buscarTimePeloNome(String nome) {
		final Query query = em.createQuery("select t from Time t where t.nome = :nome");
		query.setParameter("nome", nome);
		
		List<Time> times = query.getResultList();
		
		if(times.size() > 0) {
			return times.get(0);
		} else {
			return null;
		}
	}
	
	public Time buscarTimePeloId(long id) {
		final Query query = em.createQuery("select t from Time t where t.id = :id");
		query.setParameter("id", id);
		
		List<Time> times = query.getResultList();
		
		if(times.size() > 0) {
			return times.get(0);
		} else {
			return null;
		}
	}
	
	public void removerTime(Time time) {
		super.remove(time);
	}
	
	public List<Time> timePorCapitao(String capitao) {
		final Query query = em.createQuery("select t from Time t where t.capitao = :capitao");
		query.setParameter("capitao", capitao);
		List<Time> times = query.getResultList();
		if(times.size() > 0) {
			return times;
		} else {
			return null;
		}
	}
	
	public void atualizarTime(Time time) {
		Time timeCadastrado = (Time) super.find(Time.class, time.getId());
		
		time.setCapitao(timeCadastrado.getCapitao());
		
		super.update(time);
	}
}
